package com.heim.kafka.stream;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

/**
 * ClassName: KafkaStreamHelloListener
 * Package: com.heim.kafka.stream
 * Description:
 *
 * @Author 周阳阳
 * @Create 2024/10/24 17:02
 * @Version 1.0
 */
@Configuration
@Slf4j
public class KafkaStreamHelloListener {
    @Bean
    public KStream<String,String> kStream(StreamsBuilder streamsBuilder){
        //创建kstream对象，同时指定从哪个topic中接收消息
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input");
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
                    /**
                     * 处理消息的value值
                     * @param value
                     * @return
                     */
                    @Override
                    public Iterable<String> apply(String value) {
                        String[] valAry = value.split(" ");
                        return Arrays.asList(valAry);
                    }
                })       //按照value进行聚合处理
                .groupBy((key,value)->value)
                //时间窗口
                .windowedBy(TimeWindows.of(Duration.ofSeconds(1)))
                //统计单词的个数
                .count()
                //转换为stream对象
                .toStream()
                .map((key,value)->{
                    System.out.println("key:" + key + ",value:" + value);
                    return new KeyValue<>(key.key().toString(),value.toString());
                }).to("itcast-topic-out"); //发送消息
        return stream;
    }
}
